<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use App\Models\video\CommentModel;
use App\Models\video\OperateModeModel;
use App\Models\video\ReplyModel;
use App\Models\video\VideoUserModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CommentController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ['getCommentList']; //不校验openid
        parent::__construct($request);
    }

    // 获取评论列表
    public function getCommentList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 20;
        $type = $request->commentType ?: 1; // 1视频，2课程，3动态
        $id = $request->belongId ?: 0;
        $sortName = $request->sortName ? Str::snake($request->sortName) : "create_time";
        $sortOrder = $request->sortOrder ?: "desc";
        $data = CommentModel::getList("id,user_id,contents,discuss_num,praise_num,tread_num,create_time", ["mall_id" => $request->mallData["id"], "type" => $type, "status" => 1, "belong_id" => $id], $page, $pageSize, $sortName, $sortOrder);
        foreach ($data["list"] as &$item){
            $item["userPraiseStatus"] = 0;
            $item["userTreadStatus"] = 0;
            if(empty($havingData[$item["userId"]])){
                $havingData[$item["userId"]] = VideoUserModel::getFields("avatar,nickname", ["id" => $item["userId"]]);
            }
            $item["userName"] = isset($havingData[$item["userId"]]["nickname"]) ? $havingData[$item["userId"]]["nickname"] : "";
            $item["userAvatar"] = isset($havingData[$item["userId"]]["avatar"]) ? $havingData[$item["userId"]]["avatar"] : "";
            if ($request->token && $userId = $this->getTokenVar($request->token, "id")) {
                $item["userPraiseStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $item["id"], "type" => 1, "mode" => 1]);
                $item["userTreadStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $item["id"], "type" => 1, "mode" => 2]);
            }
            $item["timeText"] = UpTools::handleTimeToText($item["createTime"]);
            $item["replyCount"] = ReplyModel::getCount(["comment_id" => $item["id"], "status" => 1]);
            $data["count"] = $data["count"] + $item["replyCount"];
            $item["replyList"] = ReplyModel::query()->select("id", "parent_id", "user_id", "contents", "praise_num", "tread_num", "create_time")
                ->where(["comment_id" => $item["id"], "status" => 1])
                ->skip(0)->take(3)->orderBy("create_time", "asc")
                ->get();
            if(!empty($item["replyList"])){
                $item["replyList"] = ReplyModel::transferField($item["replyList"]->toArray());
                foreach ($item["replyList"] as &$it){
                    if(empty($havingData[$it["userId"]])){
                        $havingData[$it["userId"]] = VideoUserModel::getFields("avatar,nickname", ["id" => $it["userId"]]);
                    }
                    if($it["parentId"]) {
                        if (empty($havingData[$it["parentId"]])) {
                            $havingData[$it["parentId"]] = VideoUserModel::getFields("avatar,nickname", ["id" => $it["parentId"]]);
                        }
                        $it["parentName"] = isset($havingData[$it["parentId"]]["nickname"]) ? $havingData[$it["parentId"]]["nickname"] : "";
                    }
                    $it["userName"] = isset($havingData[$it["userId"]]["nickname"]) ? $havingData[$it["userId"]]["nickname"] : "";
                    $it["userAvatar"] = isset($havingData[$it["userId"]]["avatar"]) ? $havingData[$it["userId"]]["avatar"] : "";
                    if(!empty($userId)) {
                        $it["userPraiseStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $it["id"], "type" => 2, "mode" => 1]);
                        $it["userTreadStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $it["id"], "type" => 2, "mode" => 2]);
                    }else{
                        $it["userPraiseStatus"] = 0;
                        $it["userTreadStatus"] = 0;
                    }
                    $it["timeText"] = UpTools::handleTimeToText($it["createTime"]);
                }
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    public function getCommentDetail(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "评论ID"));
        }
        $data = CommentModel::getFields("id,user_id,contents,discuss_num,praise_num,tread_num,create_time", ["id" => $request->id]);
        $data["userPraiseStatus"] = 0;
        $data["userTreadStatus"] = 0;
        $userData = VideoUserModel::getFields("avatar,nickname", ["id" => $data["userId"]]);
        $data["userName"] = $userData["nickname"];
        $data["userAvatar"] = $userData["avatar"];
        if ($request->token && $userId = $this->getTokenVar($request->token, "id")) {
            $data["userPraiseStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $data["id"], "type" => 1, "mode" => 1]);
            $data["userTreadStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $data["id"], "type" => 1, "mode" => 2]);
        }
        $data["timeText"] = UpTools::handleTimeToText($data["createTime"]);
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 30;
        $sortName = $request->sortName ? Str::snake($request->sortName) : "create_time";
        $sortOrder = $request->sortOrder ?: "asc";
        $replyList = ReplyModel::getList(["id", "parent_id", "user_id", "contents", "praise_num", "tread_num", "create_time"], ["comment_id" => $data["id"], "status" => 1], $page, $pageSize, $sortName, $sortOrder);
        if(!empty($replyList["list"])){
            foreach ($replyList["list"] as &$it){
                if(empty($havingData[$it["userId"]])){
                    $havingData[$it["userId"]] = VideoUserModel::getFields("avatar,nickname", ["id" => $it["userId"]]);
                }
                if($it["parentId"]) {
                    if (empty($havingData[$it["parentId"]])) {
                        $havingData[$it["parentId"]] = VideoUserModel::getFields("avatar,nickname", ["id" => $it["parentId"]]);
                    }
                    $it["parentName"] = isset($havingData[$it["parentId"]]["nickname"]) ? $havingData[$it["parentId"]]["nickname"] : "";
                }
                $it["userName"] = isset($havingData[$it["userId"]]["nickname"]) ? $havingData[$it["userId"]]["nickname"] : "";
                $it["userAvatar"] = isset($havingData[$it["userId"]]["avatar"]) ? $havingData[$it["userId"]]["avatar"] : "";
                if(!empty($userId)) {
                    $it["userPraiseStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $it["id"], "type" => 2, "mode" => 1]);
                    $it["userTreadStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $it["id"], "type" => 2, "mode" => 2]);
                }else{
                    $it["userPraiseStatus"] = 0;
                    $it["userTreadStatus"] = 0;
                }
                $it["timeText"] = UpTools::handleTimeToText($it["createTime"]);
            }
        }
        $replyList["comment"] = $data;
        $this->returnData["data"] = $replyList;
        return $this->return_result($this->returnData);
    }

    // 发表评论
    public function toPublishComment(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->commentType){
            return $this->return_result(ErrorCode::code("params_not_exist", "评论类型"));
        }
        if(!$request->belongId){
            return $this->return_result(ErrorCode::code("params_not_exist", "belongId"));
        }
        if(!$request->contents){
            return $this->return_result(ErrorCode::code("params_not_exist", "内容"));
        }
        CommentModel::toAdd([
            "user_id" => $request->userLoginData["id"], "belong_id" => $request->belongId, "contents" => $request->contents, "type" => $request->commentType, "status" => 1
        ]);
        return $this->return_result($this->returnData);
    }

    // 回复评论
    public function toReplyComment(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->commentId){
            return $this->return_result(ErrorCode::code("params_not_exist", "评论ID"));
        }
        if(!$request->contents){
            return $this->return_result(ErrorCode::code("params_not_exist", "内容"));
        }
        ReplyModel::toAdd([
            "comment_id" => $request->commentId, "parent_id" => $request->parentId ?: 0, "user_id" => $request->userLoginData["id"], "contents" => $request->contents, "status" => 1
        ]);
        return $this->return_result($this->returnData);
    }

    // 删除评论
    public function toDelComment(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "评论ID"));
        }
        if(!$request->type){
            return $this->return_result(ErrorCode::code("params_not_exist", "类型"));
        }
        if($request->type == '1') {
            CommentModel::delByFilter(["id" => $request->id, "user_id" => $request->userLoginData["id"]]);
        }else{
            if(ReplyModel::getCount(["id" => $request->id, "user_id" => $request->userLoginData["id"]])) {
                ReplyModel::delById($request->id);
            }
        }
        return $this->return_result($this->returnData);
    }

    // 赞评论和回复
    public function toPraiseComment(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "评论ID"));
        }
        if(!$request->type){
            return $this->return_result(ErrorCode::code("params_not_exist", "类型"));
        }
        if($request->type == '1') { // 评论
            if(CommentModel::getCount(["id" => $request->id])) {
                if (empty(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 1]))) {
                    OperateModeModel::toAdd(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 1]);
                    CommentModel::doUpdate(["praise_num" => DB::raw("praise_num+1")], ["id" => $request->id]);
                    if(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 2])){
                        OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 2]);
                        CommentModel::doUpdate(["tread_num" => DB::raw("tread_num-1")], ["id" => $request->id]);
                    }
                } else {
                    OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 1]);
                    CommentModel::doUpdate(["praise_num" => DB::raw("praise_num-1")], ["id" => $request->id]);
                }
            }
        }else{ // 回复
            if(ReplyModel::getCount(["id" => $request->id])) {
                if (empty(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 1]))) {
                    OperateModeModel::toAdd(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 1]);
                    ReplyModel::doUpdate(["praise_num" => DB::raw("praise_num+1")], ["id" => $request->id]);
                    if(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 2])){
                        OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 2]);
                        ReplyModel::doUpdate(["tread_num" => DB::raw("tread_num-1")], ["id" => $request->id]);
                    }
                } else {
                    OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 1]);
                    ReplyModel::doUpdate(["praise_num" => DB::raw("praise_num-1")], ["id" => $request->id]);
                }
            }
        }
        return $this->return_result($this->returnData);
    }

    // 踩评论和回复
    public function toTreadComment(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "评论ID"));
        }
        if(!$request->type){
            return $this->return_result(ErrorCode::code("params_not_exist", "类型"));
        }
        if($request->type == '1') { // 评论
            if(CommentModel::getCount(["id" => $request->id])) {
                if (empty(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 2]))) {
                    OperateModeModel::toAdd(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 2]);
                    CommentModel::doUpdate(["tread_num" => DB::raw("tread_num+1")], ["id" => $request->id]);
                    if(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 1])){ // 踩了就要去除赞
                        OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 1]);
                        CommentModel::doUpdate(["praise_num" => DB::raw("praise_num-1")], ["id" => $request->id]);
                    }
                } else {
                    OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 1, "mode" => 2]);
                    CommentModel::doUpdate(["tread_num" => DB::raw("tread_num-1")], ["id" => $request->id]);
                }
            }
        }else{ // 回复
            if(ReplyModel::getCount(["id" => $request->id])) {
                if (empty(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 2]))) {
                    OperateModeModel::toAdd(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 2]);
                    ReplyModel::doUpdate(["tread_num" => DB::raw("tread_num+1")], ["id" => $request->id]);
                    if(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 1])){ // 踩了就要去除赞
                        OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 1]);
                        ReplyModel::doUpdate(["praise_num" => DB::raw("praise_num-1")], ["id" => $request->id]);
                    }
                } else {
                    OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 2, "mode" => 2]);
                    ReplyModel::doUpdate(["tread_num" => DB::raw("tread_num-1")], ["id" => $request->id]);
                }
            }
        }
        return $this->return_result($this->returnData);
    }
}
